#include "threadPool.h"
char base_addr[200]="/home/lh/project1";
int connectmysql(MYSQL *mysql)
{
    if (!mysql) {
        fprintf(stderr, "mysql_init() 失败\n");
        return 1;
    }
    mysql=mysql_real_connect(mysql,"localhost","root","2887","test",0,NULL,0);
    printf("11111\n");
    if (!mysql) {
        fprintf(stderr, "连接失败: %s\n", mysql_error(mysql));
        return 1;                                                   
    }
    return 0;
}

int threadPoolInit(threadPool_t *pthreadPool,int workerNum){
    tidArrInit(&pthreadPool->tidArr, workerNum);
    taskQueueInit(&pthreadPool->taskQueue);
    pthread_mutex_init(&pthreadPool->mutex, NULL);
    pthread_cond_init(&pthreadPool->cond, NULL);
    pthreadPool->exitFlag = 0;
    return 0;
}


int recvCommandPacket(int netfd,int *cmd,int *length,char *addr)
{
    bzero(addr,strlen(addr));
    int j=0;
    recv(netfd,cmd,sizeof(int),MSG_WAITALL);
    recv(netfd,length,sizeof(int),MSG_WAITALL);
    if(*length==0)
    {
        *length=1;
        j=1;
    }
    recv(netfd,addr,*length,MSG_WAITALL);
    if(j==1)
    {
        *length=0;
    }

    return 0;
}

int recvn(int sockfd, void *buf, ssize_t length){
    char *p = (char *)buf;//char* 是因为偏移以1个字节为单位
    ssize_t cursize = 0;
    while(cursize < length){
        ssize_t sret = recv(sockfd,p+cursize,length-cursize,0);
        cursize += sret;
    }
    return 0;
}

//下载
int getsFunc(int sockfd, char *filename) {
    int file_len=strlen(filename);
    send(sockfd,&file_len,sizeof(int),MSG_NOSIGNAL);
    send(sockfd,filename,file_len,MSG_NOSIGNAL);
    off_t filesize;
    recv(sockfd,&filesize,sizeof(off_t),MSG_WAITALL);
    if(filesize==-1)
    {
        printf("no such file\n");                          
        return 0;
    }
    else
    {
        printf("filesize=%ld\n",filesize);
    }
    int fd=open(filename,O_RDWR|O_CREAT|O_TRUNC,0666);
    char buf[4096]={0};
    int cursize=0;
    while(cursize<filesize)
    {
        int recvsize=filesize-cursize;
        if(recvsize>=4096)
            recvsize=4096;
        int ret=recv(sockfd,buf,recvsize,MSG_WAITALL);
        write(fd,buf,ret);
        cursize+=recvsize;
    }    return 0;
}

//上传文件
int putsFunc(int netfd, char *filename) {
    int file_len;
    recv(netfd,&file_len,sizeof(file_len),MSG_WAITALL);
    recv(netfd,filename,file_len,MSG_WAITALL);
    int access_ret = access(filename, F_OK);
    int fd;
    off_t filesize;
    if (access_ret == -1)
    {
        //发送-1给对面i
        off_t a=(off_t)access_ret;
        send(netfd,&a,sizeof(off_t),MSG_NOSIGNAL);
        printf("no such file\n");
        return 0;
    }
    else
    {
        fd=open(filename,O_RDWR);
        struct stat statbuf;
        fd=open(filename,O_RDWR);
        fstat(fd,&statbuf);
        filesize=statbuf.st_size;
        send(netfd,&filesize,sizeof(off_t),MSG_NOSIGNAL);
    }
    sendfile(netfd,fd,NULL,filesize);
    return 0;
}



